package com.zhiwang.planet.mvvm.viewmodel.my

import android.annotation.SuppressLint
import androidx.paging.PagedList
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.PageIndexRequest
import com.zhiwang.planet.mvvm.viewmodel.zygote.SimplePageKeyedDataSource
import com.zhiwang.planet.mvvm.viewmodel.zygote.SimplePageKeyedDataSourceFactory
import com.zhiwang.planet.mvvm.viewmodel.zygote.SimplePageKeyedRepository
import com.zhiwang.planet.ui.my.record.CommonItemData
import com.zhiwang.planet.util.responseFunc
import javax.inject.Inject

class BeanDetailDataSourceFactory constructor(restApi: RestApi): SimplePageKeyedDataSourceFactory<Int, CommonItemData>(restApi) {

    override fun createDataSource(): SimplePageKeyedDataSource<Int, CommonItemData> = BeanDetailDataSource(restApi)
}



class BeanDetailRepository @Inject constructor(restApi: RestApi) : SimplePageKeyedRepository<BeanDetailDataSourceFactory, Int, CommonItemData>(restApi)


class BeanDetailDataSource constructor(restApi: RestApi) : SimplePageKeyedDataSource<Int, CommonItemData>(restApi) {




    @SuppressLint("CheckResult")
    override fun initLoad(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, CommonItemData>) {

        refreshingState.postValue(PagedList.LoadState.LOADING)

        restApi.getEnergyRecord(PageIndexRequest((1)))
                .responseFunc()
                .subscribe({

                    callback.onResult(it.recordList, 0, 2)
                    refreshingState.postValue(PagedList.LoadState.DONE)

                }, {
                    errState.postValue(it)
                    refreshingState.postValue(PagedList.LoadState.DONE)

                }, {

                })
    }

    @SuppressLint("CheckResult")
    override fun loadNextPage(key: Int, callback: LoadCallback<Int, CommonItemData>) {
        refreshingState.postValue(PagedList.LoadState.LOADING)

        restApi.getEnergyRecord(PageIndexRequest((key)))
                .responseFunc()
                .subscribe({

                    callback.onResult(it.recordList, key + 1)
                    refreshingState.postValue(PagedList.LoadState.DONE)

                }, {
                    errState.postValue(it)
                    refreshingState.postValue(PagedList.LoadState.DONE)

                }, {

                })
    }


}